<?php

namespace App\Services\Com;

use App\Models\Messages\Message;
use App\Services\Member\MemberService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use PhpParser\Node\Expr\Cast\Object_;

use App\Services\Easemob\Messages as EasemobMessages;


/**
 * 
    发送通知 调用示例
    $param['type'] = '111';//您的限时任务即将结束！
    $param['place'] = '9';// 9是限定任务
    $param['route_link'] = 'route_link';//此任务跳转路由
    $param['owner_uuid'] = null;//空是系统发
    $param['time_limit_task_name'] = '我是限定任务名';
    $param['time_limit_task_time_rang'] = '2022-10-01 - 2022-10-21';
    $param['time_limit_task_progress'] = '任务进度-2个评论,1个好友,探店';
    $param['time_limit_task_promo_code'] = 'code:132456789aa1a';
    $param['time_limit_task_act_link'] = '/act/task_act_link';
    //接收者
    $membersUuid = ['3d7fedd4-2bdd-4d13-8dc9-4a5d77c6955e','7afa4823-c1b2-476b-8265-55cdff409d26'];
    $ret = MessageService::sendMessage($param, $membersUuid);
    var_dump($ret); 
 **/

class MessageService
{
    /**
     * 发送通知
     * @param array $param 消息内容参数
     *      [
     *          type => 消息类型，// 参考这个里面的类型Message::$messageTemplateMap
     *          place => 业务模块id 1新闻 2投票 3活动 4店铺 5推文 6用户 7talking 8 任务，9限定任务
     *          service_type 
     *          service_uuid
     *          all_context => 完整消息内容,有的需求截取16字符
     *          owner_uuid => 发消息的uuid, 空就是系统发送
     *          route_link => 跳转路由
     *          //限定任务参数 
     *          time_limit_task_name => 任务名
     *          time_limit_task_time_rang => 任务开始结束时间
     *          time_limit_task_progress => 任务进度-2个评论/1个好友/探店
     *          time_limit_task_promo_code => 2
     *          time_limit_task_act_link => 活动链接
     *      ]
     *      all_context = 发送的完整内容
     * @param array $membersUuid 接收的用户的UUID 数组
     *         ['uuid1', 'uuid2']
     * @param object $membersInfo 发送人的用户信息  空就是系统
     * @return bool
     * 
     * @throws \Exception
     */
    public static function sendMessage(array $param = [], array $membersUuid = [], $membersInfo = null)
    {
        try {
            $push = 1;
            foreach ($membersUuid as $m_key => $member_uuid) {
                $notify_arr[$member_uuid] = MemberService::getNotifySettings($member_uuid);
                //全部的开关为关，则直接返回
                if($notify_arr[$member_uuid]['all'] == 0){
                    $push = 0;
                }
                //活动信息
                if($notify_arr[$member_uuid]['act'] == 0){
                    if( in_array($param['type'], Message::$messageListType['act'])){
                        $push = 0;
                    }
                    
                }
                //动态评论、动态点赞
                if($notify_arr[$member_uuid]['circle'] == 0){
                    if( in_array($param['type'], Message::$messageListType['circle'])){
                        $push = 0;
                    }
                }
            }
            
            $serviceTypeTitleMaps   = [
                2 => '投票',
                3 => '活动',
                4 => '店铺',
                5 => '推文',
                6 => '用户',
                7 => 'Talking',
                8 => '任务',
                9 => '限定任务',
            ];
            $context                = Message::$messageTemplateMap[$param['type']]['context'] ?? '';
            $cLength                = !empty($param['all_context']) ? mb_strlen($param['all_context']) : 0;
            $place                  = isset($param['place']) && !empty($param['place']) ? $param['place'] : ($param['service_type'] ?? 7);

            //内容替换
            $findData               = [
                "{nickname}"    => $membersInfo->nickname ?? '',
                "{sex}"         => ($membersInfo->sex ?? '') == 1 ? '他' : '她',
                "{place_title}" => $serviceTypeTitleMaps[$place] ?? '',
                "{context_16}"  => ($cLength > 16) ? mb_substr($param['all_context'] ?? '', 0, 16) . '...' : ($param['all_context'] ?? ''),
                "{context_all}" => isset($param['all_context']) ? $param['all_context'] : '',
                // 限定任务
                "{time_limit_task_name}" => $param['time_limit_task_name'] ?? '',//109
                "{time_limit_task_time_rang}" => $param['time_limit_task_time_rang'] ?? '',//110
                "{time_limit_task_progress}" => $param['time_limit_task_progress'] ?? '',//111
                "{time_limit_task_promo_code}" => $param['time_limit_task_promo_code'] ?? '',//112
                "{time_limit_task_act_link}" => $param['time_limit_task_act_link'] ?? '', //112
            ];
            $findData['{datetime}'] = date("Y-m-d H:i:s");
            if (!empty($findData)) {
                $context = static::templateReplace($context, $findData);
            }

            $param['context'] = $context;

            if (empty($param['title'])) {
                $param['title'] = static::templateReplace(Message::$messageTemplateMap[$param['type']]['title'] ?? '', $findData);

            }
            if (!empty($membersInfo->uuid)) {
                $param['owner_uuid'] = $membersInfo->uuid;
            }
            //Log::info('最终发送消息内容', $param);
            DB::beginTransaction();

            unset($param['all_context']);

            //路由处理
            switch ($param['type']) {
                case 0: //评论
                case 1: //点赞
                    $param['route_link'] = $param['route_link'] ?? '';
                    break;
                case 5: //谁报名了你的活动
                        $param['route_link'] = '/app/ActUserActivity';
                    break;
                case 3: //关注了你
                case 4: //谁送礼物给你
                case 6: //您的好友给你打招呼
                    $param['route_link'] = '/app/UserInfoActivity?params_data='.$membersInfo->uuid;    
                    break;
                case 7: //活动报名结束
                case 8: //活动还有一天开始
                case 10: //活动还有一天开始
                    $param['route_link'] = '/app/ActInfoActivity?params_data='.$param['service_uuid'];
                    break;
            }
            //end

            $result = Message::create($param);

            // 批量插入 每次插入5000条
            $membersUuidChunk = array_chunk($membersUuid, 5000);

            // 批量写入
            foreach ($membersUuidChunk as $value) {
                foreach ($value as $member) {
                    $data    = [
                        'uuid'             => Str::uuid(),
                        'member_uuid'      => $member,
                        'send_member_uuid' => $param['owner_uuid'] ?? 'system',
                        'service_type'     => empty($param['service_type']) ? ($param['place'] ?? '') : $param['service_type'],
                        'service_uuid'     => $param['service_uuid'] ?? '',
                        'message_id'       => $result->id,
                        'type'             => $param['type'],
                    ];
                    $datas[] = $data;
                }

                \App\Models\Member\Message::insert($datas);

                //第三方 推送消息接口
                if($push == 1){
                    $push_data['member_uuid']   = $member;
                    $push_data['title']         = $param['title'];
                    $push_data['content']       = $param['context'];
                    $push_data['ext']['router'] = $param['route_link'] ?? '';
                    EasemobMessages::pushMsg($push_data);
                }else{
                    if( env('LOG_DEBUG') != false ){
                        Log::info(var_export($param, true).var_export($membersUuid, true));
                    }
                }
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
//            Log::alert($e->getMessage());
            throw new \Exception($e->getMessage());
        }
    }


    public static function templateReplace($context = '', $replaceDatas = [])
    {

        if (empty($context)) {
            return '';
        }

        $findData    = array_keys($replaceDatas);
        $replaceData = array_values($replaceDatas);
        return str_replace($findData, $replaceData, $context);
    }


}
